﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using Zws.Common;

namespace Zws.Frameworker.Filter
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly IHostEnvironment _hostEnvironment;

        public GlobalExceptionFilter(IHostEnvironment hostEnvironment)
        {
            _hostEnvironment = hostEnvironment;
        }

        public void OnException(ExceptionContext context)
        {
            if (!_hostEnvironment.IsDevelopment())
            {
                context.Result = CreateApiResult(context.Exception.Message);
            }
            else
            {
                context.Result = CreateApiResult(context.Exception.ToString()); ;
            }
        }

        private static JsonResult CreateApiResult(string message)
        {
            return new JsonResult(new ApiResult<object>(StatusCode.ERROR, message));
        }
    }
}
